<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理用户信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名或昵称"
            v-model="param.keyword"
            class="input-with-select"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="username" label="用户名称"> </el-table-column>
        <el-table-column prop="nickName" label="昵称"> </el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <img :src="scope.row.icon" class="usericon" />
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :formatter="dateFormat"
          label="创建时间"
        >
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>

        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="param.pageNum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="param.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 主体区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>

          <el-form-item label="昵称">
            <el-input v-model="addForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

           <el-form-item label="角色">
            <el-select v-model="addForm.roleId" placeholder="请选择">
              <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.name"
                :value="role.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="头像">
            <el-upload
              class="upload-demo"
              :action="objData.host"
              :before-upload="ossPolicy"
              :data="objData"
              :limit="1"
              :on-success="handleUploadSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
           
            </el-upload>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="addForm.note"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 主体区域 -->
        <el-form
          :model="editForm"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="editForm.password"></el-input>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="editForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editForm.note"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser(editForm.id)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }

      const regx = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

      if (regx.test(value)) {
        callback()
      } else {
        return callback(new Error('邮箱格式错误'))
      }
    }

    return {
      param: {
        pageSize: 3,
        pageNum: 1,
        keyword: '',
      },
      userList: [],
      total: null,
      // 控制对话框出现
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        nickName: '',
        note: '',
        icon: '',
        roleId:'',
      },
      roleList: [],
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
      },
      //OSS验证对象
      objData: {
        OSSAccessKeyId: '',
        policy: '',
        signature: '',
        host: '',
        dir: '',
        key: '',
      },
    }
  },
  mounted() {
    this.getUserList()
    this.getRoleList() 
  },
  methods: {
       getRoleList() {
      this.$http
        .get('role/list', { params: this.param })
        .then((result) => {
          this.roleList = result.data.list
          this.total = result.data.total
        })
        .catch((err) => {})
    },
    getUserList() {
      this.$http.get('admin/list', { params: this.param }).then((result) => {
        this.userList = result.data.list
        this.total = result.data.total
      })
    },
    handleSizeChange(newSize) {
      this.param.pageSize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPageNum) {
      this.param.pageNum = newPageNum
      this.getUserList()
    },
    // 显示编辑框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('admin/' + id)
      this.editForm = res
    },
    //修改用户信息
    editUser(id) {
      // 进行校验
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return this.$message.error('格式校验失败！')

        this.$http
          .post('admin/update/' + id, this.editForm)
          .then((result) => {
            this.editDialogVisible = false
            this.getUserList()
            this.$message.success('修改成功')
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err) // 取消删除

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const res = await this.$http.post('admin/delete/' + id)
      if (res.code == 200) {
        this.$message.success('删除成功')
        this.getUserList()
      } else {
        this.$message.error('删除失败')
      }
    },
    dateFormat(date) {
      if (date.createTime) {
        return moment(date.createTime).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    addDialogClosed() {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
      Object.assign(this.$data.objData, this.$options.data().objData)
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error('格式校验失败！')

        this.$http
          .post('admin/register', this.addForm)
          .then((result) => {
            this.addDialogVisible = false
            this.getUserList()
            this.$message.success('添加成功')
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 上传图片至OSS
    ossPolicy(file) {
      let _slef = this
      //在上传前进行服务器签名
      return new Promise((resolve, reject) => {
        // 请求后端
        this.$http
          .get('/aliyun/oss/policy')
          .then((result) => {
            _slef.objData.OSSAccessKeyId = result.data.accessKeyId
            _slef.objData.policy = result.data.policy
            _slef.objData.signature = result.data.signature
            _slef.objData.host = result.data.host // 直传OSS的服务器地址
            _slef.objData.dir = result.data.dir
            _slef.objData.key =
              result.data.dir +  '/${filename}'
            this.addForm.icon = _slef.objData.key
            resolve(true)
          })
          .catch((err) => {
            console.log(err)
            resolve(false) //停止上传 true是继续上传
          })
      })
    },
    // 图片上传成功后获取文件名
    handleUploadSuccess(res, file) {
       
        let url = this.objData.host + '/' + this.objData.dir + '/' + file.name;
        if(this.addDialogVisible){
          this.addForm.icon = url
        }
      }
  },
}
</script>

<style lang="less" scoped>
.usericon {
  width: 35px;
  height: 35px;
  padding-left: 40%;
}
</style>
